var Psytest = function (widget) {
	var self = this;
	this.widgetUid = 'psytest'+window.parseInt(Math.random()*1000000000);
	this.widget = $($(widget)[0]);
	this.expoStart = 0;
	
	this.wordStat = {};
	
	this.model = {
		position : ko.observable(-1),
		words : ko.observableArray([]),
		stat : ko.observableArray([]),
		exposing : ko.observable(false),
		goNext : function () {
			self.next();
		}
	};
	this.model.message = ko.dependentObservable(function () {
		return this.words()[this.position()];
	}, this.model);

	this.model.endOfList = ko.dependentObservable(function () {
		return this.position() >= this.words().length;
	}, this.model);
	
	this.model.startOfList = ko.dependentObservable(function () {
		return this.position() < 0;
	}, this.model);
	
	
	this.initTemplates();
	
	$.template('templateWordStat', this.templates.stat);
	this.widget.html(this.templates.iface);

	ko.applyBindings(this.model, this.widget[0]);
};

Psytest.prototype.initTemplates = function () {
	this.templates = {};
	for (var tplId in this.defaultTemplates) {
		if(this.defaultTemplates.hasOwnProperty(tplId)) {
			this.templates[tplId] = this.defaultTemplates[tplId];
		}
	}
};

Psytest.prototype.defaultTemplates = {
	iface : 
		'<div data-bind="visible:endOfList">\
			<h3>Результаты теста:</h3>\
			<div data-bind="template:\'templateWordStat\'">\
			</div>\
		</div>\
		<div data-bind="visible:!endOfList()">\
			<div data-bind="visible:startOfList">\
				<div>\
					Нажимайте ОК, как только прочитаете и поймете слово.\
				</div>\
				<div>\
					<button data-bind="click: goNext">Поехали!</button>\
				</div>\
			</div>\
			<div data-bind="visible:exposing">\
				<div>\
					<big data-bind="text:message"></big>\
				</div>\
				<div>\
					<button data-bind="click: goNext">OK</button>\
				</div>\
			</div>\
		</div>',
	stat : '<table>\
			{{each stat}}\
			<tr><td>${word}</td><td>${delay}</td></tr>\
			{{/each}}\
		</table>'
};

Psytest.prototype.setWords = function (words) {
	this.model.words(words);
	this.model.position(-1);
};
Psytest.prototype.expose = function () {
	this.model.exposing(true);
	this.expoStart = new Date;
};
Psytest.prototype.hide = function () {
	var expoStop = new Date,
		delay = expoStop.getTime() - this.expoStart.getTime();
	
	this.wordStat[this.model.words()[this.model.position()]] = delay;
	
	this.model.exposing(false);
};
Psytest.prototype.next = function () {
	var self = this;
	if(this.model.exposing()) {
		this.hide();
	}
	this.model.position(this.model.position() + 1);
	if(this.model.endOfList()) {
		this.showStat();
	} else {
		window.setTimeout(function () {
			self.expose();
		}, 500);
	}
};
Psytest.prototype.showStat = function () {
	var statTable = [];
	for (var word in this.wordStat) {
		if(this.wordStat.hasOwnProperty(word)) {
			statTable.push({word:word, delay:this.wordStat[word]});
		}
	}
	this.model.stat(statTable);
};
